<?php
function explodeGameTime($time){
    $explode = explode('-', $time);
    if($time=='' || empty($explode[0]) || empty($explode[1])){
        return '';
    }else{
        return date('Y-m-d H:i:s', $explode[0]) . ' - '. date('Y-m-d H:i:s', $explode[1]);
    }
}
function changeGameTime($time){
    $arr = explode(' - ', $time);
    return strtotime($arr[0]) . '-' . strtotime($arr[1]);
}


function deleteDir($dir){
    if ($handle = @opendir($dir)) {
        while (($file = readdir($handle)) !== false) {
            if (($file == ".") || ($file == "..")) {
                continue;
            }
            if (is_dir($dir . '/' . $file)) {
                deleteDir($dir . '/' . $file);
            } else {
                unlink($dir . '/' . $file);
            }
        }
        @closedir($handle);
        rmdir ($dir);
    }
}

function formatCard($len){
    $newStr = '';
    for ($i=0; $i < strlen($len); $i++) {
        if($i%4 == 0 && $i!=0){
            $newStr .= '-';
        }
        $newStr .= $len[$i];
    }
    return $newStr;
}

function sumCount($arr, $param){
    $sum = 0;
    foreach ($arr as $k => $v) {
        $sum += $v[$param];
    }
    return $sum;
}

function transPinyin($param){
    import("pinyin.ChinesePinyin");
    $Pinyin = new \ChinesePinyin();
    $name = $Pinyin->TransformWithoutTone($param);
    $rs = strtolower($name);
    return empty($rs) ? $param : $rs;
}

function changeTimestamp($timestamp){
    $arr = explode('-', $timestamp);
    $time1 = $arr[0]=='' ? 0 : $arr[0];
    $time2 = $arr[1]=='' ? 0 : $arr[1];

    if($time1==0 && $time2==0){
        return '待定中';
    }else{
        return date('Y-m-d H:i:s', $time1) . ' - ' . date('Y-m-d H:i:s', $time2);
    }
}

//订单跨年时用到
function explodeDate($date){
    if($date){
        $arr = explode(' - ', $date);
        $data['start_time'] = strtotime($arr[0]);
        $data['end_time'] = strtotime($arr[1])+86399;

        if(date('Y', $data['start_time']) !== date('Y', $data['end_time'])){
            return ['msg'=>'订单数据不支持跨年查询', 'result'=>false];
        }
    }else{
        //为空查询今天
        $data['start_time'] = strtotime(date("Y-m-d"));
        $data['end_time'] = time();
    }
    return ['data'=>$data, 'result'=>true];
}

//正常范围时间用到
function explodeTime($date){
    if($date){
        if(strlen($date) == 23){ //分割年月日
            $arr = explode(' - ', $date);
            $data['start_time'] = strtotime($arr[0]);
            $data['end_time'] = strtotime($arr[1])+86399;
        }else{ //分割年月
            $arr = explode(' - ', $date);
            $data['start_time'] = strtotime("{$arr[0]}-1");
            $data['end_time'] = strtotime("{$arr[1]} +1 month")-1;
        }
    }else{
        $data['start_time'] = strtotime(date("Y-m-d"));
        $data['end_time'] = time();
    }
    return $data;
}

function array_sort(array $array,$key,$order=1){
    $sort=array();
    //    在此处形成字段值与键名的对应关系
    foreach($array as $k=>$v){
        $sort[$v[$key]]=isset($sort[$v[$key]])?array_merge($sort[$v[$key]],array($k)):array($k);
    }
    if($order==1&&ksort($sort)){
        //        升序排序

    }elseif($order==0&&krsort($sort)){

    }else{
        return false;
    }
    $rs = array();
    //    按照排好顺序的关系生成新的数组
    foreach($sort as $value){
        foreach($value as $n){
            $rs[] = $array[$n];
        }
    }
    unset($sort,$array);
    return $rs;
}

//二维数组排序
function arraySequence($array, $field, $sort = 'SORT_DESC')
{
    $arrSort = array();
    if(!$array) return [];
    foreach ($array as $uniqid => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$uniqid] = $value;
        }
    }
    array_multisort($arrSort[$field], constant($sort), $array);
    return $array;
}

//二维数组的值是否存在
function issetArrayVal($parents, $searched, $val) {
    if (empty($searched) || empty($parents)) {
        return false;
    }

    foreach ($parents as $key => $value) {
        $exists = true;
        foreach ($searched as $skey => $svalue) {
            $exists = ($exists && IsSet($parents[$key][$skey]) && $parents[$key][$skey] == $svalue);
        }
//        if($exists){ return $key; }
        if($exists){ return $val=='pay_money' ? round($value[$val],2) : $value[$val]; }
    }

    return false;
}

//图表用到，没有该小时填充0
function chartHourZero($arr, $key, $val, $time){
    $addData = [];
    for($i=0; $i<$time; $i++){
        $d = $i < 10 ? 0 . $i : $i;
        if( $rs = issetArrayVal($arr, [$key=>$d], $val) ){
            $addData[] = (int)$rs;
        }else{
            $addData[] = 0;
        }
    }
    return $addData;
}

//图表用到，天数补0
function chartDayZero($arr, $key, $val, $day1, $day2, $groupType){
    $addData = [];
    if($groupType=='%m-%d'){
        for ($start = $day1; $start <= $day2; $start += 24 * 3600) {
            if( $rs = issetArrayVal($arr, [$key=>date('m-d',$start)], $val) ){
                $addData[] = (int)$rs;
            }else{
                $addData[] = 0;
            }
        }
    }else{
        $i = false;
        while( $day1 < strtotime('-1 Month', $day2) ) {
            $day1 = !$i ? strtotime('+0 Month', $day1) : strtotime('+1 Month', $day1);
            $i = true;
            if( $rs = issetArrayVal($arr, [$key=>date('Y-m',$day1)], $val) ){
                $addData[] = (int)$rs;
            }else{
                $addData[] = 0;
            }
        }
    }

    return $addData;
}

//导出Excel表格
function exportExcel($data,$excelFileName,$sheetTitle){
    import("php_excel.PHPExcel");

    /* 实例化类 */
    $objPHPExcel = new \PHPExcel();

    /* 设置输出的excel文件为2007兼容格式 */
    //$objWriter=new PHPExcel_Writer_Excel5($objPHPExcel);
//    $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);//2007版本
    $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);//非2007格式

    /* 设置当前的sheet */
    $objPHPExcel->setActiveSheetIndex(0);

    $objActSheet = $objPHPExcel->getActiveSheet();

    /*设置宽度*/
    $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(15);
    $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(15);

    /* sheet标题 */
    $objActSheet->setTitle($sheetTitle);

    $i = 1;
    foreach($data as $value){
        $j = 'A';
        foreach($value as $value2){
            $objActSheet->setCellValue($j.$i,$value2);
            if($i == 1){
                $objActSheet->getStyle($j.$i,$value2)->getFont()->getColor()->setARGB(\PHPExcel_Style_Color::COLOR_WHITE);
                $objActSheet->getStyle($j.$i,$value2)->getFont()->setBold(true);
                $objActSheet->getStyle($j.$i,$value2)->getFont()->setSize(11);
                $objActSheet->getStyle($j.$i,$value2)->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID);
                $objActSheet->getStyle($j.$i,$value2)->getFill()->getStartColor()->setRGB("4575d6");
            }
            $j++;
        }
        $i++;
    }

    /* 生成到浏览器，提供下载 */
    ob_end_clean();  //清空缓存
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");
    header('Content-Disposition:attachment;filename="'.$excelFileName.'.xls"');
    header("Content-Transfer-Encoding:binary");
    $objWriter->save('php://output');
}


//从数组中获取字段值，不存在则返回默认值
function get_array_value($array,$key,$default = ''){
    $value = isset($array[$key]) ? $array[$key] : $default;
    return $value;
}

/**
 * 中文字符串中间变星号
 * @param $user_name
 * @return string
 */
function substr_cut($user_name){
    //获取字符串长度
    $strlen = mb_strlen($user_name, 'utf-8');
    //如果字符创长度小于2，不做任何处理
    if ($strlen < 2) {
        return $user_name;
    } else {
        //mb_substr — 获取字符串的部分
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        //str_repeat — 重复一个字符串
        return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}

/**
 * 身份证号保留左右两边4位，中间变星号
 * @param $idCard
 * @return mixed|string
 */
function idcard_cut($idCard){
    return strlen($idCard)==15 ? substr_replace($idCard,"****",4,7) : (strlen($idCard)==18 ? substr_replace($idCard,"****",4,10) : "身份证位数不正常！");
}

//获取全球唯一标示guid
function get_guid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);
    $uuid = '';
    $uuid.=substr($charid, 0, 8).$hyphen;
    $uuid.=substr($charid, 8, 4).$hyphen;
    $uuid.=substr($charid,12, 4).$hyphen;
    $uuid.=substr($charid,16, 4).$hyphen;
    $uuid.=substr($charid,20,12);

    return $uuid;
}

/**
 * 转成
 * array(
 * 	'1000' => '米娱'
 * );
 * @param  [type] $table 表
 * @param  [type] $key   成为键的字段
 * @param  [type] $val   成为值的字段
 * @param  [type] $where 条件
 * @return [type] 返回数组
 */
function changeValKey($table, $key, $val, $where=''){
    $data = model($table)->field("{$key}, {$val}")->where($where)->select();
    $newData = [];
    foreach($data as $k=>$v){
        $newData[$v[$key]] = $v[$val];
    }
    return $newData;
}


/**
 * 生成密码
 */
function make_random_password( $length = 6 ) {
    // 密码字符集，可任意添加你需要的字符
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y','z', '0', '1', '2', '3',
        '4', '5', '6', '7', '8', '9');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys = array_rand($chars, $length);

    $secret = '';
    for($i = 0; $i < $length; $i++) {
        // 将 $length 个数组元素连接成字符串
        $secret .= $chars[$keys[$i]];
    }

    return $secret;
}

/**
 * 获取随机加密秘钥,全球唯一
 */
function get_random_key($upCase=false) {
    $str=microtime().rand(0,100000).get_guid();
    $str1=sha1($str);
    //$str1='mytest_'.md5($str);
    return $upCase?$str1:strtoupper($str1);
}

function make_session_id($myUserId,$channelId){
    $redis=new \app\common\model\Redis();
    $sessionId=$redis->get("user:$channelId:sessionid:$myUserId");
    if($sessionId){
        return $sessionId;
    }else{
        $sessionId=dechex($myUserId).'-'.$channelId.'-'.substr(md5(get_guid()), 8, 16);
        $redis->set("user:$channelId:sessionid:$myUserId",$sessionId,config('user_session_ttl'));
        //dd($sessionId);
        return $sessionId;
    }


}
function get_user_by_session_id($sessionId){
    $arr=explode("-",$sessionId);
    if(isset($arr[0])&&isset($arr[1])&&is_numeric($arr[1])){
        return ['my_user_id'=>hexdec($arr[0]),'channel_id'=>$arr[1]];
    }else{
        \think\Log::record('获取用户id和渠道id失败,session_id:'.$sessionId);
        throw new \think\exception\HttpException(200,'获取用户id和渠道id失败');
    }
}

/**
 * 身份证号保留左右两边4位，中间变星号
 * @param $idCard
 * @return mixed|string
 */
function id_card_cut($idCard){
    return strlen($idCard)==15 ? substr_replace($idCard,"****",4,7) : (strlen($idCard)==18 ? substr_replace($idCard,"****",4,10) : "身份证位数不正常！");
}

function p($data){
    $str='<pre style="display: block;padding: 9.5px;margin: 44px 0 0 0;font-size: 13px;line-height: 1.42857;color: #333;word-break: break-all;word-wrap: break-word;background-color: #F5F5F5;border: 1px solid #CCC;border-radius: 4px;">';
    if (is_bool($data)) {
        $show_data=$data ? 'true' : 'false';
    }elseif (is_null($data)) {
        $show_data='null';
    }else{
        $show_data=print_r($data,true);
    }
    $str.=$show_data;
    $str.='</pre>';
    echo $str;
    exit;
}

/*
 * ftp上传到cnd
 * */
function ftpToCDN($saveFath, $localFile){
    import('ftp.Ftp');
    $ftp = new \Ftp();
    $cdnData['server'] = config('cdn_config.host');//服务器地址(IP or domain)
    $cdnData['username'] = config('cdn_config.username');//ftp帐户
    $cdnData['password'] = config('cdn_config.password');//ftp密码
    $cdnData['port'] = config('cdn_config.port');//ftp端口,默认为21
    $cdnData['pasv'] = true;//是否开启被动模式,true开启,默认不开启
    $cdnData['ssl'] = false;//ssl连接,默认不开启
    $cdnData['timeout'] = config('cdn_config.timeout');//超时时间,默认60,单位 s

    if( $ftp->start($cdnData) ){
        //检测目录&创建目录
        //$remotedir = '/SdkUc/userHead';
        //if (!$ftp->chdir($saveFath)) {
        //    $ftp->mkdir($saveFath);
        //}
        //$ftp->rmdir($dirname);//删除目录
        //$ftp->delete($filename);//删除文件
        //$ftp->nlist($dirname);//返回目录列表
        if($ftp->put($saveFath,$localFile)) {
            @unlink($localFile);
            $ftp->close();
            return true;
        }else{
            $ftp->close();
            return false;
        }
    }
}

/**
 * ftp删除文件
 */
function ftpDelCDN($fileName){
    import('ftp.Ftp');
    $ftp = new \Ftp();
    $cdnData['server'] = config('cdn_config.host');//服务器地址(IP or domain)
    $cdnData['username'] = config('cdn_config.username');//ftp帐户
    $cdnData['password'] = config('cdn_config.password');//ftp密码
    $cdnData['port'] = config('cdn_config.port');//ftp端口,默认为21
    $cdnData['pasv'] = true;//是否开启被动模式,true开启,默认不开启
    $cdnData['ssl'] = false;//ssl连接,默认不开启
    $cdnData['timeout'] = config('cdn_config.timeout');//超时时间,默认60,单位 s

    if($ftp->start($cdnData)) {
        if($ftp->delete(config('cdn_userhead_path')  . $fileName)) {
            $ftp->close();
        }
    }
}

//php异步处理fsockopen
function doRequest($url, $param=array()){
    $urlinfo = parse_url($url);
    $host = $urlinfo['host'];
    $path = $urlinfo['path'];
    $query = isset($param)? http_build_query($param) : '';
    $port = 80;
    $errno = 0;
    $errstr = '';
    $timeout = 10;
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    trace($fp, 'log');
    $out = "POST ".$path." HTTP/1.1\r\n";
    $out .= "host:".$host."\r\n";
    $out .= "content-length:".strlen($query)."\r\n";
    $out .= "content-type:application/x-www-form-urlencoded\r\n";
    $out .= "connection:close\r\n\r\n";
    $out .= $query;
    fputs($fp, $out);
    fclose($fp);
}

function sum_ascii($str){
    $md5=md5($str);
    $sum=0;
    $length=strlen($md5);
    for($i=0;$i<$length;$i++){
        $char=substr($md5,$i,1);
        $sum+=ord($char);
    }
    return $sum;
}

function get_user_table($myUserName){
    return 'user_hash_'.sum_ascii($myUserName)%36;
}

//生成32位随机数
function createRandom($length){
    $base = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $baseLength = strlen($base);

    $randomString = '';
    for ($i = 0; $i < $length; $i ++) {
        $randomString .= $base[rand(0, $baseLength - 1)];
    }

    return $randomString;
}

//加密sign
function createSign($signArray, $key){
    ksort($signArray);
    $signString = urldecode(http_build_query($signArray));
    $result = strtoupper(md5($signString.'&key='.$key));

    return $result;
}

/**
 * 发送HTTP请求方法
 * @param $url
 * @param $params
 * @param string $method
 * @param array $header
 * @param bool $multi
 * @return mixed
 */
function http($url, $params, $method = 'GET', $header = array(), $multi = false){
    $opts = array(
        CURLOPT_TIMEOUT        => 10,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        //CURLOPT_HTTPHEADER     => $header,
        //CURLOPT_HEADER => 0
    );
    /* 根据请求类型设置特定参数 */
    switch(strtoupper($method)){
        case 'GET':
            if(empty($params)){
                $getUrl=$url;
            }else{
                $query=http_build_query($params);
                if(strpos($url,'?')){
                    if(substr($url,-1)=='&'){
                        $getUrl=$url.$query;
                    }else{
                        $getUrl=$url.'&'.$query;
                    }
                }else{
                    $getUrl=$url.'?'.$query;
                }
            }
            $opts[CURLOPT_URL] = $getUrl;
            break;
        case 'POST':
            //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;
            break;
        default:
            throw new \think\exception\HttpException(200,'不支持的请求方式！');
    }
    /* 初始化并执行curl请求 */
    $ch = curl_init();
    curl_setopt_array($ch, $opts);
    $data  = curl_exec($ch);
    $error = curl_error($ch);
    curl_close($ch);
    if($error) throw new \think\exception\HttpException(200,'请求发生错误：' . $error);
    return  $data;
}
function post_data($url, array $query_data,$type='query') {
    if($type=='query'){
        $post_str=http_build_query($query_data);
        $header = array(
            "Content-Type:application/x-www-form-urlencoded;charset=UTF-8"
        );
    }elseif($type=='json'){
        $post_str = json_encode($query_data);
        $header = array(
            "Content-Type:application/json;charset=UTF-8"
        );
    }else{
        return "未知的请求类型";
    }

    $curl = curl_init(); // 初始化curl
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
    curl_setopt($curl, CURLOPT_POST, 1); // post传输数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_str); // post传输数据
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3); // 设置等待时间

    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //https 请求
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $data = curl_exec($curl);
    $error = curl_error($curl);
    curl_close($curl);
    if($error){
        return $error;
    }else{
        return $data;
    }

}
function solveDomain(){
    if(isset($_SERVER['HTTP_REFERER'])){
        $pos = strpos($_SERVER['HTTP_REFERER'], '?');
        $url = substr($_SERVER['HTTP_REFERER'], 0, $pos-1);

        if(strstr($url, 'http://h.miyuhaiwai.com')){
            header("Access-Control-Allow-Origin: http://h.miyuhaiwai.com");
        }else if(strstr($url, 'http://cdn.miyuhaiwai.com')){
            header("Access-Control-Allow-Origin: http://cdn.miyuhaiwai.com");
        }else if(strstr($url, 'http://node.zhuwenbo.cc')){
            header("Access-Control-Allow-Origin: http://node.zhuwenbo.cc");
        }else if(strstr($url, 'http://admin.miyuhaiwai.com')){
            header("Access-Control-Allow-Origin: http://admin.miyuhaiwai.com");
        }else if(strstr($url, 'http://manage.miyu.my')){
            header("Access-Control-Allow-Origin: http://manage.miyu.my");
        }

        header("Access-Control-Allow-Credentials: true");
        header("Access-Control-Allow-Headers: device");
        header("Access-Control-Request-Method:GET,POST");
        if(strtoupper($_SERVER['REQUEST_METHOD'])== 'OPTIONS'){
            exit;
        }
    }
}

function http_post_data($url, array $data){
    $post_str = http_build_query($data);

    $curl = curl_init(); // 初始化curl
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0); // 过滤HTTP头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 显示输出结果
    curl_setopt($curl, CURLOPT_POST, 1); // post传输数据
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_str); // post传输数据
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3); // 设置等待时间
    $header = array(
        "Content-Type:application/x-www-form-urlencoded;charset=UTF-8"
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    //https 请求
    if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $return_content = curl_exec($curl);
    curl_close($curl);
    return $return_content;
}

function curl_file($url, $file, $gameId){
    if (class_exists('\CURLFile')) {
        $field = array('file' => new \CURLFile(realpath($file)));
    } else {
        $field = array('file' => '@' . realpath($file));
    }
    $field['game_id'] = $gameId;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    if (class_exists('\CURLFile')) {
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
    } else {
        if (defined('CURLOPT_SAFE_UPLOAD')) {
            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
        }
    }
    curl_setopt($ch, CURLOPT_POSTFIELDS, $field);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $rs = curl_exec($ch);
    curl_close($ch);
    return $rs;
}


/**
 * 判断字符串是否是json格式
 * @param $string
 * @return bool
 */
function is_json($string) {
 json_decode($string);
 return (json_last_error() == JSON_ERROR_NONE);
}

/**
 * 正则验证
 * @param $value
 * @param $style
 * @return bool|int
 */
function match($value,$style)
{
    if(empty($style))
        return false;
    if(empty($value))
        return false;

    if(substr($style,0,1)==='/'&&substr($style,-1)==='/'){
        $match=$style;
    }else{
        switch($style){
            case 'USERNAME':
                $match="/^[a-zA-Z0-9_-]{4,20}$/";
                break;
            case 'PHONE':
                $match="/^1[0-9_-]{10,10}$/";
                break;
            case 'EMAIL':
                $match='/^[\w\d]+[\wd-.]*@[w\d-.]+\.[\w\d]{2,10}$/i';
                break;
            case 'PASSWORD':
                $match="/^[a-zA-Z0-9_-]{1,64}$/";
                break;
            case 'ORDERTABLES':
                $match="/^sdk_pay_order_y_20[0-9][0-9]$/";
                break;
            default:
                return false;
        }
    }
    return preg_match($match,$value);
}

/**
 * 返回错误信息数组
 * @param string $msg
 * @param string $data
 * @return array
 */
function err($msg='error',$data=[]){
    return ['result'=>0,'msg'=>$msg,'data'=>$data];
}

/**
 * 返回成功信息数组
 * @param string $msg
 * @param array $data
 * @return array
 */
function suc($msg='ok',$data=[]){
    if(is_array($msg)){
        $data=$msg;
        return ['result'=>1,'msg'=>'ok','data'=>$data];
    }else{
        return ['result'=>1,'msg'=>$msg,'data'=>$data];
    }
}

/**
 * 检查返回结果
 * @param $data
 * @return bool
 */
function check($data){
    if(is_array($data)&&isset($data['result'])&&isset($data['msg'])&&(isset($data['data']))){
        if($data['result']===1){
            return true;
        }else{
            return false;
        }
    }else{
        return $data;
    }

}

/**
 * 通过订单号获取订单所在的表名
 * @param $myOrderId
 * @return string
 */
function get_order_table($myOrderId){
    if(match($myOrderId,"/^MYtest[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,6,2);
    }elseif(match($myOrderId,"/^MY[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,2,2);
    }elseif(match($myOrderId,"/^D[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }elseif(match($myOrderId,"/^[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,0,2);
    }elseif(match($myOrderId,"/^H[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }else{
        $year=date('Y',time());
    }
    return 'pay_order_y_'.$year;
}

/**
 * 通过订单号获取订单通知表所在的表名
 * @param $myOrderId
 * @return string
 */
function get_notify_table($myOrderId){
    if(match($myOrderId,"/^MYtest[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,6,2);
    }elseif(match($myOrderId,"/^MY[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,2,2);
    }elseif(match($myOrderId,"/^D[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }elseif(match($myOrderId,"/^[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,0,2);
    }elseif(match($myOrderId,"/^H[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }else{
        $year=date('Y',time());
    }
    return 'notify_log_y_'.$year;
}

function get_order_log_table($myOrderId){
    if(match($myOrderId,"/^MYtest[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,6,2);
    }elseif(match($myOrderId,"/^MY[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,2,2);
    }elseif(match($myOrderId,"/^D[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }elseif(match($myOrderId,"/^[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,0,2);
    }elseif(match($myOrderId,"/^H[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }else{
        $year=date('Y',time());
    }
    return 'notify_log_y_'.$year;
}

/**
 * 获取订单的年份
 * @param $myOrderId
 * @return bool|string
 */
function get_order_year($myOrderId){
    if(match($myOrderId,"/^MYtest[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,6,2);
    }elseif(match($myOrderId,"/^MY[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,2,2);
    }elseif(match($myOrderId,"/^D[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }elseif(match($myOrderId,"/^[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,0,2);
    }elseif(match($myOrderId,"/^H[0-9]{15,17}$/")){
        $year='20'.substr($myOrderId,1,2);
    }else{
        $year=date('Y',time());
    }
    return $year;
}


function dd($obj,$filename='debug'){
    date_default_timezone_set("PRC");
    $filename = $filename == '' ? 'debug' : $filename;
    $file = $filename . '.txt';
    $content = print_r($obj, true);
    //exec("chmod 777 $file");

    $logfile = fopen($file, "a") or die("Unable to open file!");
    fwrite($logfile, '【' . date('Y-m-d H:i:s', time()) . '】');
    fwrite($logfile, "\r\n");
    fwrite($logfile, $content . "\r\n");
    fclose($logfile);

}

function log_sql($sql){
    date_default_timezone_set("PRC");
    try{
        $path=__DIR__ .DIRECTORY_SEPARATOR.'..'.DIRECTORY_SEPARATOR.'log'.DIRECTORY_SEPARATOR.'sql';
        if(!is_dir($path)){
            mkdir($path);
        }
        $file=$path.DIRECTORY_SEPARATOR.date('Ymd',time()).'.sql';
        $logfile = fopen($file, "a");
        list($msec, $sec) = explode(' ', microtime());
        $msec=$msec*1000;
        fwrite($logfile, '#【' . date('Y-m-d H:i:s', $sec) . ':'.$msec.'】');
        fwrite($logfile, "\r\n");
        //fwrite($logfile, '#[input]'.json_encode(input()));
        //fwrite($logfile, "\r\n");
        fwrite($logfile, $sql . "\r\n");
        fclose($logfile);
    }catch(\Exception $e){
        \think\Log::write($e->getMessage(),'log_sql_exception');
    }
}

function async($class,$method,$data,$syncForce=false){
    if($syncForce){
        $Class=think\Loader::model($class);
        return $Class->$method($data);
    }else {
        if (config('db_async')) {
            $Queue=think\Loader::model(config('queue_model'));
            return $Queue->push($class, $method, $data);
        } else {
            $Class = think\Loader::model($class);
            return $Class->$method($data);
        }
    }

}

/**
 * 获取数据库所有表名
 * @param $database
 * @return array
 */
function get_tables($database){
    $db=\think\Db::connect();
    $tables=$db->getTables($database);
    return $tables;
}


/**
 * 驼峰转下划线
 * @param $str
 * @return mixed
 */
function humpToLine($str){
    $str = preg_replace_callback('/([A-Z]{1})/',function($matches){
        return '_'.strtolower($matches[0]);
    },$str);
    return $str;
}

/**
 * 取代系统自带的input函数,可以获取加密的参数
 * @param string $key
 * @param null $default
 * @return string
 */
function input($key = '', $default = null, $filter = ''){
    $pos=strpos($key, '.');
    if($key!==''&&$pos===false&&$filter===''){
        $Input=\think\Loader::model('\\app\\common\\model\\Input');
        $value=$Input->get($key,'not_exist');
        if($value!=='not_exist'){
            return $value;
        }
    }
    if (0 === strpos($key, '?')) {
        $key = substr($key, 1);
        $has = true;
    }
    if ($pos = strpos($key, '.')) {
        // 指定参数来源
        list($method, $key) = explode('.', $key, 2);
        if (!in_array($method, ['get', 'post', 'put', 'patch', 'delete', 'param', 'request', 'session', 'cookie', 'server', 'env', 'path', 'file'])) {
            $key    = $method . '.' . $key;
            $method = 'param';
        }
    } else {
        // 默认为自动判断
        $method = 'param';
    }
    if (isset($has)) {
        return request()->has($key, $method, $default);
    } else {
        return request()->$method($key, $default, $filter);
    }

}

//递归删除文件，不包括文件夹
function del_dir($dir){
    $dh=opendir($dir);
    while($file=readdir($dh)){
        if($file!="." && $file!=".."){//判断是不是本目录和上级目录
            if(!is_dir($dir."/".$file)){
                unlink($dir."/".$file);
            }else{
                //递归
                deldir($dir."/".$file);
            }
        }
    }
    closedir($dh);
}
